package com.dongdongshop.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.dongdongshop.api.CartServiceApi;
import com.dongdongshop.api.GoodsServiceApi;
import com.dongdongshop.api.UserServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.domain.model.TbOrder;
import com.dongdongshop.domain.model.TbOrderItem;
import com.dongdongshop.dto.AddressDTO;
import com.dongdongshop.dto.CartDTO;
import com.dongdongshop.dto.CartDetailDTO;
import com.dongdongshop.dto.ItemDTO;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.util.UserVO;
import io.jsonwebtoken.Claims;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private UserServiceApi userServiceApi;

    @Autowired
    private CartServiceApi cartServiceApi;

    @Autowired
    private GoodsServiceApi goodsServiceApi;

    @Autowired
    private TbOrderMapper orderMapper;

    @Autowired
    private TbOrderItemMapper orderItemMapper;

    @Override
    @Transactional  //事务
    @GlobalTransactional(rollbackFor = Exception.class)//添加全局事务注解
    public void createOrder(Long addrId, Integer payType, String autharizeToken) {
        //根据地址的id, addrId查询出地址的详细信息
        Result<AddressDTO> result = userServiceApi.selectById(addrId);
        if (result.getCode() != 0){
            throw new RuntimeException("收货地址不存在");
        }
        AddressDTO addressDTO = result.getData();
        //解析用户并根据用户查询购物车(调用cartServiceApi的方法)
        Result<List<CartDTO>> listResult = cartServiceApi.selectCart(autharizeToken);
        if (listResult.getCode() != 0){
            throw new RuntimeException("此用户无购物车数据");
        }
        List<CartDTO> cartDTOList = listResult.getData();
        //获取登录用户的name和id
        //获取到用户的username
        Claims claims = JwtUtil.parseJwt(autharizeToken);
        String subject = claims.getSubject();//用户对象
        UserVO userVO = JSONUtil.toBean(subject, UserVO.class);//转成uservo类型的数据
        String username = userVO.getName();
        String userVOId = userVO.getId();
        //创建订单
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);//雪花
        //用来存储order的list集合
        List<TbOrder> orderList = new ArrayList<>();
        //用来存储order_item的list集合
        List<TbOrderItem> orderItemList = new ArrayList<>();
        //商品sku的集合, 修改库存
        List<ItemDTO> itemDTOList = new ArrayList<>();
        //保存order表
        for (CartDTO cartDTO : cartDTOList) {
            //设置tb_order的值
            TbOrder order = new TbOrder();
            Long id = snowflake.nextId();//创建订单id
            order.setOrderId(id);//订单id
            order.setPaymentType(payType.toString());//付款方式
            order.setUserId(userVOId);//用户id
            order.setBuyerNick(username);//买家昵称
            order.setBuyerRate("0");//未评价
            order.setCreateTime(new Date());//订单创建时间, 默认为当前时间点
            order.setReceiverAreaName(addressDTO.getAddress());//收货地址(详细地址)
            order.setReceiverMobile(addressDTO.getMobile());//收货人手机号码
            order.setReceiver(addressDTO.getContact());//收货人
            List<CartDetailDTO> cartDetailVOList = cartDTO.getCartDetailVOList();
            BigDecimal sumMoney = new BigDecimal(0);
            for (CartDetailDTO cartDetailDTO : cartDetailVOList) {
                //商品sku表
                ItemDTO itemDTO = new ItemDTO();
                itemDTO.setId(cartDetailDTO.getItemId());//id
                itemDTO.setNum(cartDetailDTO.getNum());//库存
                itemDTOList.add(itemDTO);//sku表的list集合
                //设置总金额
                BigDecimal totalMoney = cartDetailDTO.getTotalMoney();
                sumMoney = sumMoney.add(totalMoney);
                //设置tb_order_item的值
                TbOrderItem orderItem = new TbOrderItem();
                orderItem.setGoodsId(cartDetailDTO.getItemId());//商品spu
                Long id1 = snowflake.nextId();
                orderItem.setId(id1);//订单明细表的主键id
                orderItem.setItemId(cartDetailDTO.getItemId());//sku
                orderItem.setNum(cartDetailDTO.getNum());//购买数量
                orderItem.setPrice(cartDetailDTO.getPrice());//购买的价格
                orderItem.setOrderId(id);
                orderItem.setPicPath(cartDetailDTO.getImage());//图片
                orderItem.setSellerId(cartDetailDTO.getSellerId());//商家id
                orderItem.setTotalFee(cartDetailDTO.getTotalMoney());//小计
                orderItem.setTitle(cartDetailDTO.getTitle());
                orderItemList.add(orderItem);//order_item表的list集合

            }
            order.setPayment(sumMoney);
            order.setSellerId(cartDTO.getSellerId());//商家id
            order.setStatus("1");//当前状态为未付款
            orderList.add(order);//存进list集合
        }
        //先删除库存, 再增加至订单表, 远程调用
        Result<ItemDTO> result1 = goodsServiceApi.updateByNum(itemDTOList);
        if (result1.getCode() != 0){
            throw new RuntimeException("库存删减失败");
        }
        //批量增加至tb_order表中
        orderMapper.addOrder(orderList);
        //批量增加至tb_order_item表中
        orderItemMapper.addOrderItem(orderItemList);
        //删除redis购物车
        cartServiceApi.delCart(autharizeToken);
//        int i = 9/0;
    }

}
